<template>
  <el-dialog
    :title="title"
    :visible.sync="centerDialogVisible"
    width="30%"
    @close="close"
    :destroy-on-close="true"
  >
    <div id="main">
      <el-form label-width="80px" ref="form" :model="form" :rules="rules">
        <el-form-item label="渠道级别" prop="level">
          <el-col :span="11">
            <el-select
              v-model="form.level"
              :placeholder="请选择"
              @change="levelChange"
              :disabled="disabled"
            >
              <el-option
                v-for="item in selectData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option> </el-select
          ></el-col>
        </el-form-item>
        <el-form-item label="父级渠道" prop="parentId">
          <el-col :span="11">
            <el-cascader
              @change="levelChange"
              ref="channelCascader"
              :disabled="!form.level || form.level === 1 || disabled"
              :options="options"
              filterable
              :props="{ checkStrictly: true }"
              v-model="form.parentId"
            ></el-cascader>
          </el-col>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-col :span="11">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2 }"
              maxlength="40"
              show-word-limit
              v-model="form.name"
            ></el-input
          ></el-col>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="centerDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addObj, listSelectTree, updateObj } from "@/api/houxin/channelTree";
import { deepClone } from "@/util/util";
const selectData = [
  {
    value: 1,
    label: "一级",
  },
  {
    value: 2,
    label: "二级",
  },
  {
    value: 3,
    label: "三级",
  },
];
let rules = {
  name: [{ required: true, message: "请输入渠道名称", trigger: "change" }],
  level: [{ required: true, message: "请选择渠道级别", trigger: "change" }],
  parentId: [],
};

let validateLevel = (rule, value, callback, this_) => {
  if (value) {
    let selected = this_.$refs["channelCascader"].getCheckedNodes()[0];
    if (this_.form.level - selected.level != 1) {
      callback(new Error("请选择比渠道高一级的渠道作为父级"));
    }
    if (this_.form.id && this_.form.id == selected.value) {
      callback(new Error("自身不能作为自身父级"));
    }
  }
  callback();
};
export default {
  name: "ChannelForm",
  data() {
    return {
      centerDialogVisible: false,
      selectData: selectData,
      title: "新建渠道",
      form: {
        name: "",
        level: "",
        parentId: "",
      },
      rules: deepClone(rules),
      parentsChannelSelectData: [],
      options: [],
      disabled: false,
      findFlag: false,
    };
  },
  methods: {
    close() {
      this.rules = deepClone(rules);
      this.form.id = "";
      this.disabled = false;
      (this.title = "新建渠道"), this.$refs["form"].resetFields();
      this.$refs["form"].clearValidate();
    },
    getParentTree(e, parentId) {
      let listTree = [];
      e.find((e) => {
        listTree = [];
        listTree.push(e.id);
        if (e.id == parentId) {
          return listTree;
        } else {
          if (e.children && e.children.length > 0) {
            let find = e.children.find((x) => x.id == parentId);
            if (find) {
              return listTree.push(find.id);
            }
          }
        }
      });
      return listTree;
    },
    getParentTreeLatest(e, parentId) {
      for (const iterator of e) {
        iterator.parentsArray = e.parentsArray || [];

        if (iterator.parentId != 0) {
          iterator.parentsArray.push(iterator.parentId + "");
        }
        if (iterator.id == parentId) {
          iterator.parentsArray.push(iterator.id + "");
          this.findFlag = true;
          return iterator.parentsArray;
        } else {
          if (iterator.children && iterator.children.length > 0) {
            let result = this.getParentTreeLatest(iterator.children, parentId);
            if (this.findFlag) {
              return result;
            }
          }
        }
      }
    },
    open(call) {
      this.centerDialogVisible = true;
      listSelectTree().then((e) => {
        this.channelRecursion(e.data.data);
        if (call) {
          call(e.data.data);
        }
      });
    },
    edit(data) {
      this.title = "渠道编辑";
      this.open(() => {
        this.disabled = true;
        this.form.name = data.name;
        this.form.level = data.level;
        this.form.id = data.id;
        if (data.level != 1) {
          this.form.parentId = this.getParentTreeLatest(
            deepClone(this.options),
            data.parentId
          );
          this.findFlag = false;
          this.levelChange();
        }
      });
    },
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let saveFrom = deepClone(this.form);
          try {
            saveFrom.parentId = saveFrom.parentId[saveFrom.parentId.length - 1];
          } catch (error) {
            debugger;
          }
          if (this.form.level == 1) {
            saveFrom.parentId = 0;
          }

          if (this.form.id) {
            updateObj(saveFrom).then((r) => {
              this.$message({
                message: "编辑成功",
                type: "success",
              });
              this.$emit("refreshDataList");
              this.centerDialogVisible = false;
            });
          } else {
            addObj(saveFrom).then((r) => {
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.$emit("refreshDataList");
              this.centerDialogVisible = false;
            });
          }
        }
      });
    },
    channelRecursion(data) {
      data.forEach((v) => {
        v.label = v.name;
        v.value = v.id;
        if (v.children) {
          this.channelRecursion(v.children);
        }
      });
      this.options = data;
    },
    levelChange(e = 0) {
      if (e !== 1) {
        this.rules.parentId = [
          { required: true, message: "请选择父级渠道", trigger: "change" },
          { validator: this.validateLevel, trigger: "change" },
        ];
      } else {
        this.form.parentId = "";
        this.$refs["form"].clearValidate();
        this.rules.parentId = [];
      }
    },
    validateLevel(rule, value, callback) {
      validateLevel(rule, value, callback, this);
    },
  },
};
</script>

<style></style>
